package com.refusea.train.domain.helper

import com.refusea.train.config.mvc.WebSession
import com.refusea.train.domain.cache.RichTextCache
import com.refusea.train.domain.entity.RichText
import com.refusea.train.domain.ex.BizEx
import com.refusea.train.domain.service.CensorService
import com.refusea.train.mapper.RichTextMapper
import com.refusea.train.utils.HtmlSanitizer
import org.jsoup.Jsoup
import org.springframework.core.env.Environment
import org.springframework.stereotype.Component

/**
 * @author Zhang Yan 2024/3/30
 **/
@Component
class RichTextHelper(
    private val richTextMapper: RichTextMapper,
    private val censorService: CensorService,
    private val richTextCache: RichTextCache,
    environment: Environment,
) {

    private val dev = environment.activeProfiles.contains("dev")

    fun save(req: RichText): Int {

        if (req.schoolId != WebSession.user().schoolId) {
            throw BizEx.of("参数异常，请重新登录")
        }

        if (!HtmlSanitizer.check(req.content)) {
            throw BizEx.of("内容可能包含不允许的标签或属性，或引用了外部图片，请修改后再提交")
        }

        if (!dev) {
            val document = Jsoup.parseBodyFragment(req.content)
            val text = document.text()
            if (!censorService.textCensor(text)) {
                throw BizEx.of("内容含有违规内容，请修改后再提交")
            }
        }

        if (req.id == 0) {
            richTextMapper.insert(req)
        } else {
            richTextMapper.update(req)
            richTextCache.remove(req.id)
        }
        return req.id
    }

    fun query(req: RichText): RichText? {
        return if (req.id == 0) {
            richTextMapper.query(req)
        } else {
            richTextMapper.select(req.id)
        }
    }
}
